import tkinter as tk
from tkinterdnd2 import DND_FILES, TkinterDnD
from PIL import Image
import os

class BitmapConverter(TkinterDnD.Tk):
    def __init__(self):
        super().__init__()
        self.title("单色位图转换器")
        self.geometry("400x200")
        
        label = tk.Label(self, text="拖拽图片到此处转换为单色位图", font=("Arial", 14))
        label.pack(expand=True)
        
        self.drop_target_register(DND_FILES)
        self.dnd_bind('<<Drop>>', self.drop_files)
        
        os.makedirs("output", exist_ok=True)

    def drop_files(self, event):
        files = self.split_drop_files(event.data)
        for file_path in files:
            if file_path.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif')):
                self.convert_to_bitmap(file_path)
    
    def split_drop_files(self, data):
        result = []
        temp = ""
        in_brace = False
        for c in data:
            if c == '{':
                in_brace = True
                temp = ""
            elif c == '}':
                in_brace = False
                result.append(temp)
            elif c == ' ' and not in_brace:
                if temp:
                    result.append(temp)
                    temp = ""
            else:
                temp += c
        if temp:
            result.append(temp)
        return result

    def convert_to_bitmap(self, file_path):
        try:
            img = Image.open(file_path).convert('RGBA')
            bitmap = img.convert('1')  # 转换为单色位图
            
            # 创建透明背景，只保留纯黑部分
            result = Image.new('RGBA', bitmap.size, (0, 0, 0, 0))
            for x in range(bitmap.width):
                for y in range(bitmap.height):
                    if bitmap.getpixel((x, y)) == 0:  # 纯黑像素
                        result.putpixel((x, y), (0, 0, 0, 255))
            
            filename = os.path.splitext(os.path.basename(file_path))[0]
            output_path = f"output/{filename}_bitmap.png"
            result.save(output_path)
            
            print(f"已转换: {output_path}")
        except Exception as e:
            print(f"转换失败 {file_path}: {e}")

if __name__ == "__main__":
    app = BitmapConverter()
    app.mainloop()